package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConstant;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.user.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author lfy
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-03-18 14:44:00
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Resource
    UserInfoMapper userInfoMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Map<String,Object> login(UserInfo userInfo) throws JsonProcessingException {
        Map<String,Object> data = new HashMap<>();



        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name",userInfo.getLoginName());

        String encrypt = MD5.encrypt(userInfo.getPasswd());
        wrapper.eq("passwd",encrypt);

        List<UserInfo> list = userInfoMapper.selectList(wrapper);

        if(list != null && list.size() == 1){
            //查到数据
            //把当前登录成功的用户信息存到 redis。
            String token = UUID.randomUUID().toString().replace("-", "");
            UserInfo info = list.get(0);
            String jsonStr = objectMapper.writeValueAsString(info);

            //用户信息保存7天
            redisTemplate.opsForValue().set(RedisConstant.LOGIN_USER+token,jsonStr,RedisConstant.LOGIN_USER_TIMEOUT, TimeUnit.SECONDS);

            data.put("token",token);
            data.put("id",info.getId());
            data.put("nickName",info.getNickName());
            return data;
        }

        return null;
    }

    @Override
    public void logout(String token) {
        //删除用户在redis中的信息即可
        redisTemplate.delete(RedisConstant.LOGIN_USER+token);
    }
}




